<template>
  <div class="app-container">
    <!-- 顶部标题和用户信息 -->
    <div class="page-header">
      <h2>大健康综合管理后台</h2>
    </div>

    <!-- 页面标题和状态筛选 -->
    <div class="page-title">
      <h3>商品管理</h3>
      <div class="status-tabs">
        <el-radio-group v-model="queryParams.status" @change="handleStatusChange" size="large">
          <el-radio-button label="">全部</el-radio-button>
          <el-radio-button
              v-for="status in statusOptions"
              :key="status.code"
              :label="status.code"
          >{{ status.desc }}
          </el-radio-button>
        </el-radio-group>
      </div>
    </div>

    <!-- 操作按钮区域 -->
    <div class="operation-bar">
      <div class="left-operations">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:product:add']">
          新增
        </el-button>
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
                   v-hasPermi="['system:product:edit']">
          修改
        </el-button>
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
                   v-hasPermi="['system:product:remove']">
          删除
        </el-button>
      </div>
      <div class="right-operations">
        <el-button icon="Refresh" @click="resetQuery">刷新</el-button>
      </div>
    </div>

    <!-- 查询条件区域 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="productName">
        <el-input
            v-model="queryParams.productName"
            placeholder="请输入商品名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- 新增：商品编码查询 -->
      <el-form-item label="商品编码" prop="productCode">
        <el-input
            v-model="queryParams.productCode"
            placeholder="请输入商品编码"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="全部" value="" />
          <el-option
              v-for="status in statusOptions"
              :key="status.code"
              :label="status.desc"
              :value="status.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 商品列表表格 -->
    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange" stripe>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品ID" align="center" prop="productId" width="100" />
      <el-table-column label="商品编码" align="center" prop="productCode" width="120" />
      <el-table-column label="商品名称" align="center" prop="productName" min-width="150" />
      <el-table-column label="主图" align="center" prop="mainImage" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.mainImage" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="原价" align="center" prop="originalPrice" width="100">
        <template #default="scope">
          <span style="color: #ff5000; font-weight: bold;">¥{{ scope.row.originalPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column label="现价" align="center" prop="currentPrice" width="100">
        <template #default="scope">
          <span style="color: #ff5000; font-weight: bold;">¥{{ scope.row.currentPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column label="库存" align="center" prop="stock" width="100" />
      <el-table-column label="销量" align="center" prop="sales" width="100" />
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)" effect="light">
            {{ getStatusDesc(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:product:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:product:remove']">删除</el-button>
          <el-button
              v-if="scope.row.status === '1'"
              link type="success"
              icon="CircleCheck"
              @click="handleShelf(scope.row)"
              v-hasPermi="['system:product:edit']"
          >上架</el-button>
          <el-button
              v-if="scope.row.status === '0'"
              link type="warning"
              icon="CircleClose"
              @click="handleOffShelf(scope.row)"
              v-hasPermi="['system:product:edit']"
          >下架</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改商品对话框 -->
    <el-dialog :before-close="handleClose" :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="productRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入商品名称" />
        </el-form-item>
        <!-- 新增：商品编码字段 -->
        <el-form-item label="商品编码" prop="productCode">
          <el-input
              v-model="form.productCode"
              placeholder="请输入商品编码"
              :disabled="form.productId != null"
          />
          <div style="font-size: 12px; color: #909399; margin-top: 5px;">
            提示：商品编码一旦创建不可修改
          </div>
        </el-form-item>
        <el-form-item label="分类ID" prop="categoryId">
          <el-input v-model="form.categoryId" placeholder="请输入分类ID" />
        </el-form-item>
        <!-- 添加主图上传 -->
        <el-form-item label="主图" prop="mainImage">
          <el-upload
              class="avatar-uploader"
              :action="uploadAction"
              :headers="headers"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeUpload"

          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
                v-for="status in statusOptions"
                :key="status.code"
                :label="status.desc"
                :value="status.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="原价" prop="originalPrice">
          <el-input-number v-model="form.originalPrice" :min="0" :precision="2" style="width: 100%" />
        </el-form-item>
        <el-form-item label="现价" prop="currentPrice">
          <el-input-number v-model="form.currentPrice" :min="0" :precision="2" style="width: 100%" />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number v-model="form.stock" :min="0" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Product">
import { listProduct, getProduct, delProduct, addProduct, updateProduct, getStatusOptions } from "@/api/system/product"
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {getToken} from "@/utils/auth.js";
const { proxy } = getCurrentInstance()

const productList = ref([])
const statusOptions = ref([]) // 动态状态选项
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    productName: null,
    productCode: null,
    status: null,
  },
  rules: {
    productName: [
      { required: true, message: "商品名称不能为空", trigger: "blur" }
    ],
    productCode: [
      { required: true, message: "商品编码不能为空", trigger: "blur" },
      {
        pattern: /^[A-Za-z0-9_-]+$/,
        message: "商品编码只能包含字母、数字、下划线和横线",
        trigger: "blur"
      }
    ],
    status: [
      { required: true, message: "商品状态不能为空", trigger: "change" }
    ],
    originalPrice: [
      { required: true, message: "原价不能为空", trigger: "blur" }
    ],
    currentPrice: [
      { required: true, message: "现价不能为空", trigger: "blur" }
    ],
    stock: [
      { required: true, message: "库存不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 上传前校验 */
function beforeUpload(file) {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    proxy.$modal.msgError('上传图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    proxy.$modal.msgError('上传图片大小不能超过 2MB!')
    return false
  }
  if (form.value.productId != null) {
    //修改方法
    uploadAction.value = `${uploadUrl}/system/product/uploadImg/${form.value.productId}`
  } else {
    //新增方法
    uploadAction.value = `${uploadUrl}/common/uploadFile`
  }
  console.log('上传地址：',uploadAction.value)
  return true
}

/** 处理上传 */
//下列两行不可变
const headers = ref({ Authorization: "Bearer " + getToken() })
const uploadUrl = inject('uploadUrl')
///user/commonUser/uploadImg对应具体图片接口地址
const uploadAction = ref('')
const imageUrl = ref('')

const handleAvatarSuccess = (response, uploadFile) => {
  console.log(response)
  form.value.mainImage = response.msg
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
}
// 弹窗关闭时的处理
const handleClose = (done) => {
  const hasChanges = imageUrl.value || form.value.productName || form.value.productCode
  // 如果有未保存的图片上传，可以添加确认提示
  if (hasChanges) {
    proxy.$modal.confirm('关闭弹窗将清空已上传的图片，是否继续？').then(() => {
      reset()
      done()
    }).catch(() => {
      // 用户取消关闭，不做任何操作
    })
  } else {
    reset()
    done()
  }
}
/** 查询商品列表 */
function getList() {
  loading.value = true
  listProduct(queryParams.value).then(response => {
    productList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 获取状态选项 */
function getStatusOptionsList() {
  getStatusOptions().then(response => {
    statusOptions.value = response.data
  })
}

/** 根据状态码获取状态描述 */
function getStatusDesc(statusCode) {
  const status = statusOptions.value.find(item => item.code === statusCode)
  return status ? status.desc : '未知状态'
}

/** 根据状态码获取标签类型 */
function getStatusTagType(statusCode) {
  switch (statusCode) {
    case '0': return 'success' // 已上架
    case '1': return 'info'    // 未上架
    case '2': return 'warning' // 待审核
    case '3': return 'danger'  // 未通过
    default: return 'info'
  }
}

/** 状态筛选改变 */
function handleStatusChange(status) {
  queryParams.value.status = status
  handleQuery()
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  queryParams.value.status = null
  handleQuery()
}

/** 上架操作 */
function handleShelf(row) {
  proxy.$modal.confirm(`是否确认上架商品"${row.productName}"？`).then(() => {
    return updateProduct({ ...row, status: '0' })
  }).then(() => {
    proxy.$modal.msgSuccess("上架成功")
    getList()
  })
}

/** 下架操作 */
function handleOffShelf(row) {
  proxy.$modal.confirm(`是否确认下架商品"${row.productName}"？`).then(() => {
    return updateProduct({ ...row, status: '1' })
  }).then(() => {
    proxy.$modal.msgSuccess("下架成功")
    getList()
  })
}

// 表单重置
function reset() {
  form.value = {
    productId: null,
    productName: null,
    productCode: null,
    categoryId: null,
    mainImage: null,
    subImages: null,
    description: null,
    originalPrice: null,
    currentPrice: null,
    stock: null,
    sales: null,
    tags: null,
    isHot: null,
    isNew: null,
    isSeckill: null,
    seckillPrice: null,
    seckillStock: null,
    seckillStartTime: null,
    seckillEndTime: null,
    status: null,
    createTime: null,
    updateTime: null
  }
  imageUrl.value = '' // 清空图片预览
  uploadAction.value = '' //重置上传地址
  proxy.resetForm("productRef")
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.productId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加商品"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _productId = row.productId || ids.value
  getProduct(_productId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改商品"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["productRef"].validate(valid => {
    if (valid) {
      if (form.value.productId != null) {
        updateProduct(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addProduct(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _productIds = row.productId || ids.value
  proxy.$modal.confirm('是否确认删除商品编号为"' + _productIds + '"的数据项？').then(function() {
    return delProduct(_productIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/product/export', {
    ...queryParams.value
  }, `product_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList()
  getStatusOptionsList()
})
</script>

<style scoped>
.page-header {
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.page-title {
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.page-title h3 {
  margin: 0 0 15px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.left-operations {
  display: flex;
  align-items: center;
  gap: 10px;
}

.right-operations {
  display: flex;
  align-items: center;
}

.status-tabs {
  margin-top: 10px;
}

:deep(.el-table) {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  :deep(.el-upload:hover) {
    border-color: var(--el-color-primary);
  }
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>